//
//  Date-Extension.swift
//  时间处理
//
//  Created by 付建国 on 2016/10/13.
//  Copyright © 2016年 sher. All rights reserved.
//

import Foundation

extension Date{
    
    static func createDateStr(createAtStr : String) -> String {
        
        //创建时间格式化对象
        let fmt = DateFormatter()
        fmt.dateFormat = "EEE MM dd HH:mm:ss Z yyyy"
        fmt.locale = Locale.init(identifier: "en")
        
        //将字符串时间转化成NSDate
        guard let createDate = fmt.date(from: createAtStr) else{
            return ""
        }
        
        //创建当前时间
//        print(createDate) //2016-05-31 09:46:55 +0000
        let nowDate = Date()
        //        let nowDateStr = "Tue May 31 17:46:55 +0800 2015"
        //        let nowDate = fmt.date(from: nowDateStr)!
        
        //计算时间差
        let interval = Int (nowDate.timeIntervalSince(createDate))
        
        //对时间间隔处理
        //一天内
        if interval < 60{
            
            return "刚刚"
        }
        if interval < 60 * 60{
            
            return "\(interval / 60)分钟前"
        }
        if interval < 60 * 60 * 24 {
            
            return "\(interval / (60 * 60))小时前"
        }
        //一天后
        //创建日历对象
        let calendar = Calendar.current
        if calendar.isDateInYesterday(createDate){
            fmt.dateFormat = "昨天 HH:mm"
            let timeStr = fmt.string(from: createDate)
            
            return timeStr
        }
        //一年内
        let cmps = calendar.dateComponents([.year], from: createDate, to: nowDate)
        
        if cmps.year! < 1{
            fmt.dateFormat = "MM-dd HH:mm"
            let timeStr = fmt.string(from: createDate)
    
            return timeStr
        }
        
        //超过一年
        fmt.dateFormat = "yyyy-MM-dd HH:mm"
        let timeStr = fmt.string(from: createDate)
        
        return timeStr
    }
    
}
